package com.taxi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taxi.dto.Car;
import com.taxi.dto.DriverUser;
import com.taxi.mapper.CarMapper;
import com.taxi.remote.ServiceMapClient;
import com.taxi.response.TerminalResponse;
import com.taxi.response.TrackResponse;
import com.taxi.result.Result;
import com.taxi.service.ICarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author aniu
 * @since 2023-09-28
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {
    @Autowired
    private ServiceMapClient serviceMapClient;
    @Autowired
    private CarMapper carMapper;
    @Override
    public Result getCar(Long cid) {
        Car car = baseMapper.selectById(cid);
        return Result.ok(car);
    }

    @Override
    public Result addCar(Car car) {
        Long carId = car.getId();
        if( carId != null){  // update
            Car mysqlCar = baseMapper.selectById(carId);
            boolean empty = ObjectUtils.isEmpty(mysqlCar);
            if(empty){
                return Result.fail("无该车辆，无法更新");
            }
            baseMapper.updateById(car);
        }else{  // insert
            // 获取车辆终端tid
            TerminalResponse result = serviceMapClient.addTerminal(car.getVehicleNo(), car.getVehicleNo()).getData();
            String tid = result.getTid();
            car.setTid(tid);

            //获取车辆轨迹id
            TrackResponse data = serviceMapClient.addTrack(tid).getData();
            car.setTrid(data.getTrid());
            car.setTrname(data.getTrname());
            baseMapper.insert(car);
        }
        return Result.ok();
    }

    public Result getCarList(int page,int limit, String address, String vehicleNo){
        Page<Car> pageObj = new Page<>(page, limit);

        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Car::getState,0);
        // 如果address不为空，添加到查询条件
        if (StringUtils.isNotEmpty(address)) {
            queryWrapper.eq(Car::getAddress, address);
        }
        // 如果vehicleNo不为空，添加到查询条件
        if (StringUtils.isNotEmpty(vehicleNo)) {
            queryWrapper.eq(Car::getVehicleNo,vehicleNo);
        }

        IPage<Car> iPage = carMapper.selectPage(pageObj, queryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("items", iPage.getRecords());
        data.put("total", iPage.getTotal());
        return Result.ok(data);
    }

}
